<template>
  <el-dialog
    v-model="visible"
    title="📊 资产同步中"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="!isSyncing"
    @close="handleClose"
  >
    <div class="sync-dialog-content">
      <div class="sync-info">
        <div class="info-item">
          <span class="label">任务名称:</span>
          <span class="value">{{ taskName }}</span>
        </div>
        <div class="info-item" v-if="!isSyncing">
          <span class="label" style="width: 140px">网管扫描任务:</span>
          <el-select
            v-model="selectedNetworkTask"
            placeholder="请选择网管扫描任务"
            style="width: 100%"
            filterable
            :loading="loadingNetworkTasks"
          >
            <el-option
              v-for="task in networkTaskList"
              :key="task.id"
              :label="task.task_name"
              :value="task.id"
            >
              <span>{{ task.task_name }}</span>
            </el-option>
          </el-select>
        </div>
        <div class="info-item" v-else>
          <span class="label">网管扫描任务:</span>
          <span class="value">{{ selectedNetworkTaskName }}</span>
        </div>
      </div>

      <div v-if="isSyncing" class="sync-progress">
        <el-progress
          :percentage="progress"
          :status="progressStatus"
          :stroke-width="20"
        />
        <div class="progress-text">
          {{ currentStatus }}
          {{
            processedCount > 0
              ? `已处理 ${processedCount}/${totalCount} 个IP`
              : ""
          }}
        </div>
      </div>

      <div v-if="isSyncing" class="sync-time">
        <span class="label">开始时间:</span>
        <span class="value">{{ startTime }}</span>
      </div>

      <div v-if="errorMessage" class="error-message">
        <el-alert
          :title="errorMessage"
          type="error"
          :closable="false"
          show-icon
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!isSyncing && !isCompleted"
          type="primary"
          @click="handleStartSync"
          :disabled="!selectedNetworkTask || loadingNetworkTasks"
          :loading="starting"
        >
          开始同步
        </el-button>
        <el-button
          v-if="isCompleted || errorMessage"
          type="primary"
          @click="handleClose"
        >
          关闭
        </el-button>
        <el-button v-if="isSyncing && !isCompleted" disabled>
          同步中...
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, onUnmounted } from "vue";
import { syncAssetsV2, getSyncStatus, queryNetworkTasks } from "@/api/task";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";

interface Props {
  modelValue: boolean;
  taskName: string;
  taskId: number;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  taskName: "",
  taskId: 0,
});

const emit = defineEmits<{
  "update:modelValue": [value: boolean];
  close: [];
}>();

const visible = ref(false);
const starting = ref(false);
const isSyncing = ref(false);
const isCompleted = ref(false);
const progress = ref(0);
const progressStatus = ref<"success" | "exception" | "warning" | undefined>(
  undefined
);
const currentStatus = ref("准备中...");
const processedCount = ref(0);
const totalCount = ref(0);
const startTime = ref("");
const errorMessage = ref("");
const runId = ref("");

// 网管扫描任务相关
const networkTaskList = ref<Array<{ id: number; task_name: string }>>([]);
const selectedNetworkTask = ref<number | null>(null);
const selectedNetworkTaskName = ref("");
const loadingNetworkTasks = ref(false);

let pollTimer: NodeJS.Timeout | null = null;

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    visible.value = newVal;
    if (newVal) {
      loadNetworkTasks();
      resetState();
    } else {
      stopPolling();
    }
  }
);

// 监听选中的网管任务变化，更新任务名称
watch(selectedNetworkTask, (newVal) => {
  if (newVal) {
    const task = networkTaskList.value.find((t) => t.id === newVal);
    selectedNetworkTaskName.value = task ? task.task_name : "";
  } else {
    selectedNetworkTaskName.value = "";
  }
});

// 监听 visible 变化，同步到父组件
watch(visible, (newVal) => {
  if (!newVal) {
    emit("update:modelValue", false);
    emit("close");
  }
});

// 加载网管扫描任务列表
const loadNetworkTasks = async () => {
  loadingNetworkTasks.value = true;
  try {
    const { data } = await queryNetworkTasks({
      page: 1,
      per_page: 1000,
    });

    networkTaskList.value = data.tasks;
  } catch (err) {
    console.error("获取网管扫描任务列表失败:", err);
    ElMessage.error("获取网管扫描任务列表失败");
  } finally {
    loadingNetworkTasks.value = false;
  }
};

// 重置状态
const resetState = () => {
  selectedNetworkTask.value = null;
  selectedNetworkTaskName.value = "";
  isSyncing.value = false;
  isCompleted.value = false;
  progress.value = 0;
  progressStatus.value = undefined;
  currentStatus.value = "准备中...";
  processedCount.value = 0;
  totalCount.value = 0;
  startTime.value = "";
  errorMessage.value = "";
  runId.value = "";
  stopPolling();
};

// 开始同步
const handleStartSync = async () => {
  if (!selectedNetworkTask.value) {
    ElMessage.warning("请选择网管扫描任务");
    return;
  }

  const selectedTask = networkTaskList.value.find(
    (t) => t.id === selectedNetworkTask.value
  );
  if (!selectedTask) {
    ElMessage.warning("选择的网管扫描任务不存在");
    return;
  }

  starting.value = true;
  errorMessage.value = "";

  try {
    const response = await syncAssetsV2({
       task: props.taskName,
      task_id: selectedNetworkTask.value,
    });

    // 根据设计文档，响应格式为: { code, message, run_id }
    const data = response.data || response;

    if (data.code === 2000) {
      runId.value = data.run_id || data.data?.run_id;
      isSyncing.value = true;
      startTime.value = dayjs().format("YYYY-MM-DD HH:mm:ss");
      currentStatus.value = "正在比对数据...";
      ElMessage.success(data.message || "同步任务已启动");
      startPolling();
    } else {
      errorMessage.value = data.message || "同步启动失败";
      ElMessage.error(errorMessage.value);
    }
  } catch (error: any) {
    errorMessage.value = error.message || error.data?.message || "同步启动失败";
    ElMessage.error(errorMessage.value);
  } finally {
    starting.value = false;
  }
};

// 开始轮询
const startPolling = () => {
  stopPolling();
  pollTimer = setInterval(async () => {
    if (!runId.value) return;

    try {
      const { data } = await getSyncStatus({
        run_id: runId.value,
      });

      console.log(data, "datadddd");

      const statusData = data || {};
      const status = statusData.status;

      // 更新进度
      if (statusData.progress !== undefined) {
        progress.value = statusData.progress;
      }

      // 更新处理数量（字段名是 processed 和 total）
      if (statusData.processed !== undefined) {
        processedCount.value = statusData.processed;
      }
      if (statusData.total !== undefined) {
        totalCount.value = statusData.total;
      }

      // 更新状态文本（如果有 current_status 字段）
      if (statusData.current_status) {
        currentStatus.value = statusData.current_status;
      } else if (
        statusData.message &&
        status !== "completed" &&
        status !== "failed"
      ) {
        // 如果状态不是完成或失败，显示 data.message
        currentStatus.value = statusData.message;
      }

      // 检查是否完成
      if (status === "completed") {
        isCompleted.value = true;
        isSyncing.value = false;
        progress.value = 100;
        progressStatus.value = "success";
        currentStatus.value = "同步完成";
        ElMessage.success("同步完成");
        stopPolling();
        // 2秒后自动关闭
        setTimeout(() => {
          handleClose();
        }, 2000);
      } else if (status === "failed") {
        isCompleted.value = true;
        isSyncing.value = false;
        progressStatus.value = "exception";
        // 错误消息在 data.data.message 中
        errorMessage.value = statusData.message || "同步失败";
        ElMessage.error(errorMessage.value);
        stopPolling();
      }
    } catch (error: any) {
      console.error("查询同步状态失败:", error);
      // 轮询失败不中断，继续轮询
    }
  }, 2000); // 2秒轮询一次
};

// 停止轮询
const stopPolling = () => {
  if (pollTimer) {
    clearInterval(pollTimer);
    pollTimer = null;
  }
};

// 关闭弹窗
const handleClose = () => {
  if (isSyncing.value && !isCompleted.value) {
    ElMessage.warning("同步进行中，请稍候...");
    return;
  }
  visible.value = false;
  resetState();
};

// 组件卸载时清理定时器
onUnmounted(() => {
  stopPolling();
});
</script>

<style lang="scss" scoped>
.sync-dialog-content {
  padding: 20px 0;
}

.sync-info {
  margin-bottom: 24px;

  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    .label {
      font-weight: 500;
      color: #606266;
      margin-right: 12px;
      min-width: 80px;
    }

    .value {
      color: #303133;
      flex: 1;
    }
  }
}

.sync-progress {
  margin-bottom: 24px;

  .progress-text {
    margin-top: 12px;
    text-align: center;
    color: #606266;
    font-size: 14px;
  }
}

.sync-time {
  display: flex;
  align-items: center;
  margin-bottom: 16px;

  .label {
    font-weight: 500;
    color: #606266;
    margin-right: 12px;
  }

  .value {
    color: #303133;
  }
}

.error-message {
  margin-top: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
